
from main import basedir
from flask import request
import time, os
from main.code import *
from main.utils import InterfaceHelper, RequestHelper, FileHelper, ImageHelper, EmailHelper
from main.dbs.questionnaire_db import *
from flask_restplus import Api, Resource, fields
from . import api
# 定义命名空间
ns = api.namespace('questionnaire', description='Questionnaire api')


option_model = api.model('OptionModel', {
    'id': fields.Integer(readOnly=True, description='id'),
    'answer': fields.String(description='答案'),
    'message': fields.String(description='反馈信息'),
    'status': fields.Boolean(description='状态')
})

questionnaire_model = api.model('QuestionnaireModel', {
    'id': fields.Integer(readOnly=True, description='id'),
    'question': fields.String(description='问题'),
    'options': fields.List(fields.Nested(option_model)),
    'type': fields.String(description='类型'),
    'tips': fields.String(description='提示'),
    'message': fields.String(description='反馈信息'),
    'status': fields.Boolean(description='状态')
})

questionnaire_list_model = api.model('QuestionnaireListModel', {
    'data': fields.List(fields.Nested(questionnaire_model)),
    'total': fields.Integer(description='数量'),
    'message': fields.String(description='反馈信息'),
    'status': fields.Boolean(description='状态')
})

questionnaire_commit_model = api.model('QuestionnaireCommitModel', {
    'questionnaire_id': fields.Integer(description='题号'),
    'option_id': fields.Integer(description='选项id'),
    'user_id': fields.Integer(description='用户id'),
    'content': fields.String(description='填空内容'),
    'message': fields.String(description='反馈信息'),
    'status': fields.Boolean(description='状态')

})

questionnaire_commit_list_model = api.model('QuestionnaireCommitListModel', {
    'data': fields.List(fields.Nested(questionnaire_commit_model)),
    'total': fields.Integer(description='数量'),
    'message': fields.String(description='反馈信息'),
    'status': fields.Boolean(description='状态')
})


@ns.route('/<int:user_id>')
class QuestionnaireApi(Resource):
    '''问卷接口'''

    @ns.doc("get_questionnaire_list")
    @ns.marshal_with(questionnaire_list_model)
    def get(self, user_id):
        '''获取问卷'''
        responses = {}
        if query_questionnaire_commit_by_user_id(user_id):
            return success(message="用户已填写问卷", status=False)
        questionnaire_list = []
        for i in query_questionnaire():
            options = []
            question_id = i.id
            questionnaire = i.to_json()
            for j in query_option_by_question_id(question_id):
                options.append(j.to_json())
            questionnaire['options'] = options
            questionnaire_list.append(questionnaire)
        responses['data'] = questionnaire_list
        responses['total'] = len(questionnaire_list)
        return success(responses)


@ns.route('commit/<int:user_id>')
class QuestionnaireCommitApi(Resource):
    '''问卷提交'''

    @ns.doc("post_questionnaire_list")
    @ns.expect(questionnaire_commit_list_model)
    def post(self, user_id):
        '''提交问卷'''
        parameters = RequestHelper.formToDict(request)
        questionnaire_commit_list = parameters['data']
        q_c_list = []
        for i in questionnaire_commit_list:
            questionnairecommit = JSONHelper.dictToObj(i, QuestionnaireCommit)
            questionnairecommit.user_id = user_id
            q_c_list.append(questionnairecommit)
        if not insert(q_c_list):
            return fail()
        return success()

    @ns.doc("delete_questionnaire")
    def delete(self, user_id):
        '''删除某人问卷'''
        questionnaire_commit_list = query_questionnaire_commit_by_user_id(user_id)
        if questionnaire_commit_list:
            delete(questionnaire_commit_list)
            return success()
        else:
            return success(message='questionnaire is empty', status=False)
        return fail()

@ns.route('/email/<string:email>')
class EmailApi(Resource):
    '''邮件api'''

    @ns.doc("get_email")
    def get(self, email):
        today = time.strftime('%Y-%m-%d', time.localtime())
        filename = today + ".csv"
        path = os.path.join("./main/static", filename)
        fp = open(path, "w", encoding='utf-8-sig')
        fp.write("%s,%s,%s\n" % ("题号", "答案", "提交用户"))
        for line in query():
            line = line.to_json()
            ans = ""
            if line['option'] is not None:
                ans = line['option']
            else:
                ans = line['content']
            fp.write("%s,%s,%s\n" % (line['questionnaire_id'], ans, line['user_id']))
        fp.close()
        if EmailHelper.send_email_file(email, path):
            return success()
        return fail()




